package com.ktjiaoyu.crm.realm;

import com.ktjiaoyu.crm.pojo.User;
import com.ktjiaoyu.crm.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

/**
 * @ClassName : MyShiroRealm
 * @Description :
 * @Author : Lzz
 * @Date: 2023/11/27 10:39:23
 */
public class MyShiroRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;

    /**
     * 认证
     * @param token the authentication token containing the user's principal and credentials.
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        //从token中获取用户名
        String username = usernamePasswordToken.getUsername();
        //调用数据库查询方法根据用户名查询用户信息
        User user = userService.findUserByUsrName(username);
        if(user == null) throw new UnknownAccountException();   //账号错误
        if(user.getUsrFlag()==null || user.getUsrFlag().intValue()==0) throw new LockedAccountException();  //账号是否锁定

        return new SimpleAuthenticationInfo(user,user.getUsrPassword(),getName());
    }

    /**
     * 授权
     * @param principals the primary identifying principals of the AuthorizationInfo that should be retrieved.
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }


}
